//
//  IMFileManagerController.m
//  wanzhaoIM
//
//  Created by wanzhao on 15/7/16.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "IMFileManagerController.h"
#import "IMmenueButton.h"
#import "QBImagePickerController.h"
#import "IMSelectFileCell.h"
#import "ChildHoodService.h"
#import "CFileModel.h"
#import "MicroDef.h"
#import "UIButtonFactory.h"
#import "CHChatRoomBase.h"
#import "JKAlertDialog.h"
#import "CFolderMgr.h"
#import "CAccountMgr.h"
#import "CAccountModel.h"
#import "UIUtil.h"

@interface IMFileManagerController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, weak) UIView *menueView;
@property (nonatomic, weak) IMmenueButton *selectButton;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dirArray;
@property (nonatomic, strong) NSMutableArray *fileArray;
@property (nonatomic, strong) UIImageView *imgView;
@property (nonatomic, weak) ISTThemeButton *sendButton;
@property (nonatomic , strong) UIView *toolView;
@property (nonatomic, strong) NSMutableArray *selectedArray;
@property (nonatomic, strong) NSMutableArray *AllFilesArray;
@property (nonatomic, weak) UIView *lineView;

@end

@implementation IMFileManagerController

- (void)dealloc
{
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
   self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"选择文件"];


    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.showsHorizontalScrollIndicator = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [self handlePathWithPath:self.oriPath];
    
     self.toolView = [self toolView];
    [self.view addSubview:self.toolView];
    
    
    UIView *menueView = [[UIView alloc] init];
    menueView.backgroundColor = ClearColor;
    [self.view addSubview:menueView];
    self.menueView = menueView;
    [self setupMenueView];
    
    
    
//    UIView *lineView = [[UIView alloc] init];
//    lineView.backgroundColor = RGBACOLOR(212, 212, 212, 1.0);
//    [self.menueView addSubview:lineView];
//    self.lineView = lineView;
    
}

- (void)handlePathWithPath:(NSString *)path
{
    
    NSMutableArray *arrayM = [NSMutableArray array];
    NSArray *array1 = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[ChildHoodService defaultService] personalDownloadFilePath] error:nil];
    NSArray *array2 = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[ChildHoodService defaultService] groupDownloadFilePath] error:nil];
    for (NSString *subPath in array1) {
        [arrayM addObjectsFromArray:[UIUtil handleFilePathWithPath:[[ChildHoodService defaultService] personalDownLoadFilePathWithUserId:subPath] isGroup:NO]];
    }
    for (NSString *subPath in array2) {
        [arrayM addObjectsFromArray:[UIUtil handleFilePathWithPath:[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:subPath] isGroup:YES]];
    }
    
    [self.AllFilesArray addObjectsFromArray:[arrayM sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"CreateDate" ascending:NO]]]];

}


- (NSMutableArray *)AllFilesArray
{
    if (_AllFilesArray == nil) {
        _AllFilesArray = [NSMutableArray array];
    }
    return _AllFilesArray;
}
- (NSMutableArray *)fileArray
{
    if (_fileArray == nil) {
        _fileArray = [NSMutableArray array];
    }
    return _fileArray;
}

- (NSMutableArray *)dirArray
{
    if (_dirArray == nil) {
        _dirArray = [NSMutableArray array];
    }
    return _dirArray;
}

- (NSMutableArray *)selectedArray
{
    if (_selectedArray == nil) {
        _selectedArray = [NSMutableArray array];
    }
    return _selectedArray;
}

- (UIView *)toolView
{
    UIView *toolViewTmp = [[UIView alloc] initWithFrame:CGRectMake(0, HARDWARE_SCREEN_HEIGHT - 108, HARDWARE_SCREEN_WIDTH, 44)];
    _imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, 44)];
    [_imgView setImage:[[UIImage imageNamed:@"tabbarview_background.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(43, 50, 0, 50) resizingMode:UIImageResizingModeStretch]];
    
    
    
    
    ISTThemeButton *send = [UIButtonFactory buttonWithType:UIButtonTypeCustom
                                                     title:@"发送"
                                                     frame:CGRectMake(HARDWARE_SCREEN_WIDTH - 110, 5, 100, 34)
                                                 imageName:@"wide_btn_normal.png"
                                           tappedImageName:@"wide_btn_normal.png"
                                                    target:self
                                                    action:@selector(sendMessage)
                                                       tag:1203];
    
    
    
    [send setTitleColor:RGBCOLORWITH16COLOR(0xfd8584) forState:UIControlStateNormal];
    
    [send setTitleColor:[UIUtil colorWithHexString:@"#bfc0c0" withAlpha:1] forState:UIControlStateHighlighted];
    
    
    [toolViewTmp addSubview:_imgView];

    [toolViewTmp addSubview:send];
   
    self.sendButton = send;
    
    
    
    return toolViewTmp;
}

- (void)sendMessage
{
//    if (self.selectedArray.count > 10) {
//        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"" message:@"一次最多只能上传10个文件"];
//        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
//            
//        }];
//    [alert show];
//        return;
//    }
    
    if ([self.fileManagerDelegate respondsToSelector:@selector(fileManageControllerDidSendWithSelectedArray:)]) {
        [self.fileManagerDelegate fileManageControllerDidSendWithSelectedArray:self.selectedArray];
    }
    [self.navigationController popViewControllerAnimated:YES];
    
//    [self.navigationController popViewControllerAnimated:YES];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"IMFileManagerControllerDidSendFile" object:self.selectedArray];
//    for (UIViewController *vc in self.navigationController.childViewControllers) {
//        if ([vc isKindOfClass:[CHChatRoomBase  class]]) {
//            [self.navigationController popToViewController:vc animated:YES];
//        }
//    }
}

- (void)updateSendButton
{
    if (self.selectedArray.count > 0) {
        [self.sendButton setTitle:[NSString stringWithFormat:@"发送(%zd)",self.selectedArray.count] forState:UIControlStateNormal];
    } else {
        [self.sendButton setTitle:@"发送" forState:UIControlStateNormal];
    }
}
- (void)setupMenueView
{
    [self addButtonWithTitle:@"文档" menueType:IMSelectDoc];
    [self addButtonWithTitle:@"图片" menueType:IMSelectPicture];
    [self addButtonWithTitle:@"视频" menueType:IMSelectVideo];
    [self addButtonWithTitle:@"声音" menueType:IMSelectSound];
    [self addButtonWithTitle:@"其它" menueType:IMSelectOther];
}

- (IMmenueButton *)addButtonWithTitle:(NSString *)title menueType:(IMSelectType)menueType
{
    IMmenueButton *button = [IMmenueButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(selectFile:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:title forState:UIControlStateNormal];
    button.menueType = menueType;
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    button.backgroundColor = ClearColor;
    [self.menueView addSubview:button];
    return button;
}


- (void)selectFile:(IMmenueButton *)button
{
    self.selectButton.selected = NO;
    button.selected = YES;
    self.selectButton = button;
    
    [self.fileArray removeAllObjects];
    if (button.menueType == IMSelectDoc) {
    
        for (CFileModel *fileModel in self.AllFilesArray) {
            
            if ([[UIUtil getFileIconByName:fileModel.FileName] isEqualToString:@"execlIcon"] || [[UIUtil getFileIconByName:fileModel.FileName] isEqualToString:@"wordIcon"] || [[UIUtil getFileIconByName:fileModel.FileName] isEqualToString:@"txtIcon"] || [[UIUtil getFileIconByName:fileModel.FileName] isEqualToString:@"pdfIcon"] || [[UIUtil getFileIconByName:fileModel.FileName] isEqualToString:@"pptIcon"]) {
                [self.fileArray addObject:fileModel];
            }
        }
        
    } else if (button.menueType == IMSelectPicture) {
        
        for (CFileModel *fileModel in self.AllFilesArray) {
            if ([[UIUtil getFileIconByName:fileModel.FileName] isEqualToString:@"imageIcon"]) {
                [self.fileArray addObject:fileModel];
            }
        }

        
    } else if (button.menueType == IMSelectVideo) {
    
        for (CFileModel *fileModel in self.AllFilesArray) {
            if ([[UIUtil getFileIconByName:fileModel.FileName] isEqualToString:@"mp4Icon"]) {
                [self.fileArray addObject:fileModel];
            }
        }

        
    } else if (button.menueType == IMSelectSound) {
        
        for (CFileModel *fileModel in self.AllFilesArray) {
            if ([[UIUtil getFileIconByName:fileModel.FileName] isEqualToString:@"file_wav"]) {
                [self.fileArray addObject:fileModel];
            }
        }

        
    } else if (button.menueType == IMSelectOther) {
        for (CFileModel *fileModel in self.AllFilesArray) {
            if ([[UIUtil getFileIconByName:fileModel.FileName] isEqualToString:@"othersIcon"] || [[UIUtil getFileIconByName:fileModel.FileName] isEqualToString:@"rarIcon"]) {
                [self.fileArray addObject:fileModel];
            }
        }
    }
    
    [self.tableView reloadData];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.menueView.frame = CGRectMake(0, 0, self.view.frame.size.width, 40);
//    self.lineView.frame = CGRectMake(0, 39.5, self.view.frame.size.width, 0.5);
    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.menueView.frame), self.view.frame.size.width, self.view.frame.size.height - 44 - 40);
    CGFloat btnH = 40;
    CGFloat btnW = self.view.frame.size.width / self.menueView.subviews.count;
    CGFloat btnX = 0;
    for (int i = 0; i < self.menueView.subviews.count; i ++) {
        IMmenueButton *button = self.menueView.subviews[i];
        btnX = i * btnW;
        button.frame = CGRectMake(btnX, 0, btnW, btnH);
        if (i == 0) {
            [self selectFile:button];
        }
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//        NSInteger section = 0;
//        if([self.fileArray count] > 0)
//        {
//            section ++;
//        }
//        if([self.dirArray count] > 0)
//        {
//            section ++;
//        }
    
        return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    NSInteger rows = 0;
//    switch (section) {
//        case 0:
//            if([self.dirArray count] > 0)
//            {
//                rows = [self.dirArray count];
//            }
//            else
//            {
//                rows = [self.fileArray count];
//            }
//            break;
//        case 1:
//            rows = [self.fileArray count];
//            break;
//        default:
//            rows = 0;
//            break;
//    }
    return self.fileArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CFileModel *fileModel = self.fileArray[indexPath.row];
//    switch (indexPath.section) {
//        case 0:
//        {
//            if (self.dirArray.count > 0) {
//                fileModel = self.dirArray[indexPath.row];
//            } else {
//                fileModel = self.fileArray[indexPath.row];
//            }
//        }
//            break;
//        case 1: {
//            fileModel = self.fileArray[indexPath.row];
//        }
//            break;
//        default:
//            break;
//    }
    
    IMSelectFileCell *cell = [IMSelectFileCell imSelectFileCellWithTableView:tableView];
    cell.fileModel = fileModel;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CFileModel *fileModel;
    fileModel = self.fileArray[indexPath.row];
    
    if (self.selectedArray.count >= 10 && fileModel.isHasSelected == NO) {
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"一次最多只能上传10个文件"];
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            
        }];
        [alert show];
        return;
    }
    
    
   
    fileModel.isHasSelected = !fileModel.isHasSelected;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    if (fileModel.isHasSelected) {
        [self.selectedArray addObject:fileModel];
    } else {
        [self.selectedArray removeObject:fileModel];
    }
    
    
    
    [self updateSendButton];

//    switch (indexPath.section) {
//        case 0:
//        {
//            if (self.dirArray.count > 0) {
//                fileModel = self.dirArray[indexPath.row];
//                IMFileManagerController *vc = [[IMFileManagerController alloc] init];
//                vc.fileManagerDelegate = self;
//                vc.oriPath = fileModel.LocalFilePath;
//                [self.navigationController pushViewController:vc animated:YES];
//            } else {
//                fileModel = self.fileArray[indexPath.row];
//                fileModel.isHasSelected = !fileModel.isHasSelected;
//                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//                if (fileModel.isHasSelected) {
//                    [self.selectedArray addObject:fileModel];
//                } else {
//                    [self.selectedArray removeObject:fileModel];
//                }
//                [self updateSendButton];
//            }
//        }
//            break;
//          case 1:
//        {
//           
//        }
//            break;
//        default:
//            break;
//    }
}
@end
